package com.example.browser;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class folder extends Activity {
    private ArrayList arrayList=new ArrayList();
    private ListView folder_list;
    private MyDatabaseHelper dbHelper;

    private String get_title,get_url,foldername;//暂存从数据库得到的title和url
    private int get_id; //暂存从数据库得到的id
    private boolean if_exist;
    private String titler, url;//按值查找详细信息
    int id; //按值查找id
    private TextView text_title, text_url;//书签详细信息edittext
    private EditText search_bookmark;
    private LinearLayout addfolder,addweb,history;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_folder);
        Intent it=super.getIntent();
        foldername=it.getStringExtra("foldername");
        folder_list=(ListView)findViewById(R.id.folder_list);
        addweb=(LinearLayout)findViewById(R.id.addweb) ;
        history=(LinearLayout)findViewById(R.id.history) ;
        search_bookmark=(EditText)findViewById(R.id.search_bookmark) ;
        //监听编辑框
        search_bookmark.addTextChangedListener(new folder.EditChangedListener());
        queryinfo(foldername);
        //点击函数：
        folder_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exist) {
                    Intent intent = new Intent(folder.this, webview.class);//没有任何参数（意图），只是用来传递数据
                    intent.putExtra("searchText", query_by_id(position,foldername));
                    startActivity(intent);
                    finish();
                }


            }
        });
        //长按选择删除
        folder_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (if_exist)
                    dialog_bottom(position);
                return true;
            }
        });
        addweb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog addwebdialog = new Dialog(folder.this, R.style.MyDialogActivityStyle);
                View addwebview = View.inflate(folder.this, R.layout.dialogaddweb, null);
                addwebdialog.setContentView(addwebview);
                addwebdialog.setCanceledOnTouchOutside(true);
                Window window = addwebdialog.getWindow();//得到对话框的窗口．
                WindowManager.LayoutParams wl = window.getAttributes();
                WindowManager windowManager = getWindowManager();
                Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
                wl.width = (int)(display.getWidth() * 1); //设置宽度
                wl.height = (int)(display.getHeight() * 0.35);
                wl.alpha = 1f;// 设置对话框的透明度,1f不透明
                window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
                window.setAttributes(wl);
                text_title = (EditText) addwebview.findViewById(R.id.title);
                text_url = (EditText) addwebview.findViewById(R.id.url);
                text_title.setFocusable(true);
                text_title.setFocusableInTouchMode(true);
                text_title.requestFocus();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                                   public void run() {
                                       InputMethodManager inputManager =
                                               (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                       inputManager.showSoftInput(text_title, 0);
                                   }
                               },
                        200);

                //显示详细信息

                addwebview.findViewById(R.id.addweb).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(TextUtils.isEmpty(text_title.getText().toString())||TextUtils.isEmpty(text_url.getText().toString())){
                            Toast.makeText(folder.this, "网址名和网址都不能为空", Toast.LENGTH_SHORT).show();
                        }else {
                            select(text_title.getText().toString(),text_url.getText().toString());
                            addwebdialog.dismiss();
                        }
                        queryinfo(foldername);

                    }
                });

                addwebview.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        addwebdialog.dismiss();
                    }
                });

                addwebdialog.show();

            }
        });
    }
    //查询数据库里的字段
    public void select(String title,String url) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String sql ="SELECT * FROM "+foldername+" WHERE url='"+url+"'";
        Cursor result=db.rawQuery(sql, null);
        if(result.moveToFirst())
        {

            Toast.makeText(folder.this, "已存在,名称为—"+result.getString(1), Toast.LENGTH_LONG)
                    .show();
            result.close();
            db.close();
        }
        else {
            addweb(title,url);
            result.close();
            db.close();

        }
    }
    public void addweb(String title,String url){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(folder.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", title);
        values.put("url", url);
        db.insert(foldername,null,values);
        Toast.makeText(folder.this,"添加成功",Toast.LENGTH_SHORT).show();
        queryinfo(foldername);

    }
    //删除函数：
    public void delete(int position,String tablename){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(tablename,"id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
       // arrayList.clear();
        queryinfo(foldername);
    }

    //全部删除
    public void delete_all(String tablename){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+tablename, null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete(tablename,"id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        queryinfo(foldername);
    }


    //数据库逆序查询函数：
    public void queryinfo2( String url ){
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        arrayList.clear();
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";

        String sql = "select * from "+foldername+" where url like '%"+ url + "%'OR title like '%"+ url + "%'";
        Cursor cursor=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"title","url"},
                        new int[] {R.id.title,R.id.url});
                folder_list.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "没有找到");
            map.put("url", "");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"title","url"},
                    new int[] {R.id.title,R.id.url});
            folder_list.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }

    //数据库逆序查询函数：
    public void queryinfo(String tablename){
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        arrayList.clear();
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写
        Cursor cursor = db.query(tablename, null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"title","url"},
                        new int[] {R.id.title,R.id.url});
                folder_list.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "暂时没有收藏");
            map.put("url", "此处是存放收藏地方");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"title","url"},
                    new int[] {R.id.title,R.id.url});
            folder_list.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }

    //按值查找：
    public String query_by_id(int position,String tablename){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+tablename, null);
        while (cursor.moveToNext()) {
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return url;
    }
    public int query_by_id2(int position,String tablename){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+tablename, null);
        while (cursor.moveToNext()) {
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return id;
    }
    public String query_by_id3(int position,String tablename){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+tablename, null);
        while (cursor.moveToNext()) {
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return titler;
    }

    public void move(String title,String url){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(folder.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title",title);
        values.put("url", url);
        //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
        db.insert("bookmarkDB",null,values);

        Toast.makeText(folder.this,"添加成功",Toast.LENGTH_SHORT).show();
    }

    //修改数据
    public void update(int id, String title, String url,String tablename) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="update "+tablename+" set url='" + url + "',title='" + title + "' where id="+ id;
        db.execSQL(sql);
        db.close();

    }

    //url详细信息对话框
    public void url_infomation(final int position,String tablename){
        final Dialog dialog = new Dialog(folder.this, R.style.MyDialogActivityStyle);
        View view = View.inflate(folder.this, R.layout.modification, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();//得到对话框的窗口．
        WindowManager.LayoutParams wl = window.getAttributes();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
        wl.width = (int)(display.getWidth() * 1); //设置宽度
        wl.height = (int)(display.getHeight() * 0.35);
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
        window.setAttributes(wl);
        text_title = (TextView) view.findViewById(R.id.textView2);
        text_url = (TextView) view.findViewById(R.id.textView3);

        //显示详细信息
        text_url.setText(query_by_id(position,tablename));
        text_title.setText(titler);
        view.findViewById(R.id.upDate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                update(query_by_id2(position,tablename),text_title.getText().toString(),text_url.getText().toString(),tablename);
                queryinfo(foldername);
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();


    }

    //底部对话框
    public void dialog_bottom(final int position){
        //弹出对话框

        final Dialog dialog = new Dialog(folder.this, R.style.MyDialogActivityStyle);
        View view = View.inflate(folder.this, R.layout.folderdialog, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();//得到对话框的窗口．
        WindowManager.LayoutParams wl = window.getAttributes();

        dialog.show();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
        wl.width = (int)(display.getWidth() * 1); //设置宽度
        wl.height = (int)(display.getHeight() * 0.4);
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
        window.setAttributes(wl);
        //点击事件
        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消对话框
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.move).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                move(query_by_id3(position,foldername),query_by_id(position,foldername));
                delete(position,foldername);
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除制定position，并取消对话框
               delete(position,foldername);
                dialog.dismiss();

            }
        });
        view.findViewById(R.id.lookup).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查看、修改
                dialog.dismiss();
                url_infomation(position,foldername);
            }
        });
        view.findViewById(R.id.clear_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //全部删除
                delete_all(foldername);
                dialog.dismiss();


            }
        });
    }
    //监听编辑框--https://www.jb51.net/article/135392.htm
    //https://blog.csdn.net/ycwol/article/details/46594275
    class EditChangedListener implements TextWatcher {
        public void afterTextChanged(Editable arg0) {
// 文字改变后出发事件
            String content = search_bookmark.getText().toString();
            //若输入框内容为空按钮可点击，字体为蓝色
            if (!content.isEmpty()) {
                queryinfo2(search_bookmark.getText().toString());

            } else {
                queryinfo(foldername);

            }

        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
// TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

        }
    };
    @Override
    protected void onRestart() {
        super.onRestart();

    }

}